package gw.com.android.ui.views;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.view.ViewGroup;

import com.gwtsz.gts2.hx.R;

import www.com.library.util.DeviceUtil;

/**
 * @author jett
 * @since 2018-09-13.
 */
public class StrategyTextView extends android.support.v7.widget.AppCompatTextView {

    public StrategyTextView(Context context) {
        super(context);
    }

    public StrategyTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public StrategyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setText(CharSequence text, boolean isNew) {
        setText(buildContent(text, isNew));
        post(new Runnable() {
            @Override
            public void run() {
                int lineCount = getLineCount();
                refreshHeight(lineCount == 1);
            }
        });
    }

    private CharSequence buildContent(CharSequence content, boolean isNew) {
        if (TextUtils.isEmpty(content)) {
            return "";
        }
        String text = content.toString();
        if (isNew) {
            SpannableString ss = new SpannableString(text + "  新标签");
            Drawable drawable = getResources().getDrawable(R.mipmap.a_tag_new);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            ImageSpan imageSpan = new ImageSpan(drawable) {
                @Override
                public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
                    super.draw(canvas, text, start, end, x, top, y, bottom - DeviceUtil.instance().dip2px(2, getContext()), paint);
                }
            };
            ss.setSpan(imageSpan, ss.length() - 3, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            return ss;
        } else {
            return text;
        }
    }

    private void refreshHeight(boolean singleLine) {
        int height = DeviceUtil.instance().dip2px(singleLine ? 54 : 60, getContext());
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) getLayoutParams();
        if (params.height != height) {
            params.height = height;
            setLayoutParams(params);
        }
    }

}
